Repository navigation
Phase 3: CLI login and signup on the device flow - #1289
Merged
neuromechanist merged 21 commits intoSep 7, 2026
Merged
neuromechanist merged 21 commits into
neuromechanist merged 21 commits into
Conversation
New src/lib/device-login.ts drives the device authorization grant: print the URL and code, try the browser, poll for the key with a SIGINT-cancellable, timeout-composed poll loop. loginAction rewired onto it (the --key/NEMAR_API_KEY path stays as validated paste-key fallback), sharing writeSignedInAccount/applyServerUser with statusAction --refresh (now renames on refresh and prints the Key: line) and the profile self-service commands. Exit hook suppresses the bug-report nudge for 130 (Ctrl-C during the poll). storeAccount() removed, its one caller moved. Part of #1283 (epic #1272 phase 3).
nemar auth signup runs the device flow, then fills in username, github_username, city, country via flag or prompt in one PATCH /auth/profile, requests upload access unless --no-upload-access, and reports anything the CLI cannot set. Non-TTY stdin names the missing flags and exits 1 before any prompt. collectResearcherName and lookupOrcidName are gone with the ORCID/password form. Part of #1283 (epic #1272 phase 3).
test/auth-device-cli.test.ts (41 cases: URL/code/browser, polling cadence, terminal answers, success writes the account, stale-probe re-login, active-account re-login, SIGINT, parallel logins, the server going away and back, --key, status file mode and rename, logout, keys, signup completion, deprecations, root shortcuts, --debug redaction) and test/device-login.unit.test.ts (machineName, pollDeadlineMs, accountKeyFor). Fixes a bug the stale-probe test caught: writeSignedInAccount was skipping the old device key's revoke entirely when the preflight probe found it dead, instead of only skipping the confirmation line. Part of #1283 (epic #1272 phase 3).
test/auth-device-cli-live.test.ts drives the real CLI subprocess against a deployed backend (TEST_API_URL), streaming stdout to catch the printed code and acting on the browser side through seedWebUser plus the passwordless dev_code sign-in: the full login/status/keys/ logout loop, deny, a pending account's confirm refusal, a mid-flight revoke, and signup with flags. Prod-guarded and deploy-probe-skipped like test/auth-device-flow.test.ts; the from-scratch ORCID signup path and the service-account case (test.todo) are out of reach for an automated test and are recorded for the manual walk-through on #1283. Part of #1283 (epic #1272 phase 3).
README quick start, auth command list, environment variables (NEMAR_NO_BROWSER; drops the fictional NEMAR_API_URL), and troubleshooting; AGENTS.md's user flow and CLI commands table; ADR 0047 Consequences for decisions 5-7, 10, 12 (account keying, the config file's 0600 mode, same-machine key replacement, logout's scoped revoke, and the retrieve-key/regenerate-key deprecation replacing the ADR's deferred call). Part of #1283 (epic #1272 phase 3).
📦 Package PreviewYour package is ready to test! bun install -g nemar-cli@PR1289Version: 🤖 Updated on each push. |
writeSignedInAccount's greeting now depends on source: --key/ NEMAR_API_KEY keeps the pre-phase-3 "Welcome back, <name>!" (a person pasting a key already holds an account); the device flow keeps the new "Welcome, <name>!". Pinned in test/auth-device-cli.test.ts: the --key good case asserts "Welcome back", a device success asserts "Welcome," and not "Welcome back". Fixes the integration-dev failure on PR #1289 (test/cli.test.ts:230).
applyServerUser now caches sandbox_dataset_id when the server sends one, restoring behavior the paste path had before this phase. Pinned through both login paths with a returning trained account; the stand-in's defaultUser() no longer defaults to a fresh account, so a caller that forgets to cache it fails loudly.
Only a network failure (statusCode 0) prints the "unreachable"
retry line and waits out the deadline. Any other thrown error --
a 5xx, a 200 that fails deviceTokenSuccessSchema, or a 400 with an
unrecognized code -- is now counted; three in a row end the poll
with a new "server_error" outcome instead of retrying silently
until the deadline. A success resets the count.
Also spreads the success payload before the "kind" discriminant
({ ...result.data, kind: "success" }) so a passthrough field can
never overwrite it.
pollDeviceToken now re-parses the token endpoint's 400 body against deviceTokenErrorSchema (a discriminated union) instead of probing error/reason as loose strings. reason is typed DeviceAuthRefusalCode | undefined and is never backfilled from error -- it is undefined only when the body itself failed to validate. A 400 whose error is still a terminal grant code this build recognizes ends the poll even when the body fails validation, using the body's own message when present, else DEVICE_GRANT_MESSAGES[error]. ApiError gains rawBody (the whole parsed error body), set by request() alongside the existing code/reason fields, so a caller that needs the full contract shape has it without every other caller paying for a second body it never asked for.
Config's key fields (keyId/keyName/keyCreatedAt/keySource) become a discriminated union (KeyFields in lib/config.ts): a "device" entry always carries all three, a "paste" entry carries none, and absent keySource is a password-era account. writeSignedInAccount takes a single tagged keyInfo parameter instead of two separately-typed ones that happened to always agree, so the invalid "device with no key" state cannot be constructed. A paste login explicitly clears a stale device key's fields rather than merely omitting them, so a re-login on a different path from the same machine cannot leave a no-longer-current keyId behind. AccountInfo gains "key" (the accounts-map key) and makes "username" honestly optional -- an email-keyed entry has none. switchAction's picker, logoutAction --all, and the "Other accounts" status line now use "key" to look up and revoke accounts instead of a username that could be undefined; --all previously skipped an email-keyed account entirely (switchAccount(undefined) finds nothing), which a new regression test with a mixed username/email-keyed fleet covers. Also prints a visible warning when the same-machine key revoke on login fails, instead of swallowing the error silently.
findAccountKeyByEmail returns undefined (not a guess) when two stored entries share an email, and dlogs the ambiguity -- a state this build never writes on its own, so guessing which one a re-login means risks merging the wrong account's key and cached fields into it. upsertAccount's caller lands the login as a fresh entry instead, same as no match. writeSignedInAccount now catches upsertAccount throwing (a corrupt store, an unwritable config dir): the sign-in already succeeded server-side, so a just-minted device key is best-effort revoked with itself as bearer (new revokeApiKeyWithBearer, since nothing was ever saved to authenticate the ordinary way) before reporting the failure and exiting 1, instead of an uncaught exception.
Removes every "(decision N)" citation from the phase 3 device-flow files: each either cites ADR 0047 by content where the ADR actually covers the rule, or states the rule plainly where it does not (the plan's own numbering is not something a future reader can verify against). Fixes the matching phase 1 leftover in backend/src/services/device-auth.ts. AGENTS.md's CLI table now shows -k/--key on login only, not signup. The auth/keys group verbose help spells out that a browser-based login mints a key while --key/NEMAR_API_KEY only stores one. retrieve-key/regenerate-key's verbose help gains the deprecation sentence and regenerate-key's every-machine warning. guardNonInteractive's docstring now points at confirm()'s guard instead of independently restating the inquirer failure mode. test/auth-device-cli-live.test.ts cites .github/workflows/deploy-backend.yml's push trigger instead of "AGENTS.md release pipeline" for why the dev worker deploys only from dev. config.ts: a named CONFIG_FILE_MODE constant replaces two 0o600 literals; "conf's pre-13 default" becomes "conf's default file mode (0o666, unrelated to the conf version)" in both config.ts and ADR 0047. ADR 0047 also names MAX_LIVE_API_KEYS where the 25-key cap is discussed, rejoins a mid-clause line break at the em dash, and splits an over-long line before its parenthetical.
Live test: seedWebUser now returns the seeded row's id, and the mid-flight-revoke test uses it against POST /admin/revoke/by-id/:id with an asserted 200 instead of a best-effort, swallowed call. CLI test: a password-era flat config (no "accounts" key) is migrated in place, read by auth status (with its password-era Key: line), and merged into by a later device login rather than duplicated. A live (not stale) device key's same-machine re-login still revokes and prints the replacement confirmation. invalid_grant/too_many_keys is covered alongside the other terminal codes. A SIGINT with a seeded config leaves the file byte-identical. /users/me stand-in bodies are typed from the contract (UserMeResponse) and re-parsed against userMeResponseSchema before being served, so a contract drift fails the file instead of silently serving a stale shape. The polling-gap assertion is loosened to the actual invariant (slow_down roughly doubles the gap) rather than a fixed millisecond floor. pollForDeviceToken/pollDeadlineMs take an optional graceSeconds, defaulting to DEVICE_CONFIRM_GRACE_SECONDS and never passed by the real CLI entry point. A new unit test calls it with graceSeconds: 0 against a closed port and gets "unreachable" in about a second, covering the deadline-reached give-up branch the CLI stand-in test cannot reach without waiting out the real multi-minute window; the CLI test file notes why at the relevant section.
neuromechanist
merged commit Sep 7, 2026
b54df98
into
feature/issue-1272-epic-orcid-cli-signin
12 checks passed
This was referenced Sep 7, 2026
This branch was previously deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
CLI half of ORCID-first sign-in (epic #1272, phase 3).
nemar auth loginis now the one command for first-time signup and later sign-in: it mints a device code (phase 1, ADR 0047), prints the authorize URL and the short code, tries the browser unless--no-openorNEMAR_NO_BROWSER=1, polls with the RFC 8628 backoff, and writes the key to a 0600 config file.--keyandNEMAR_API_KEYremain the paste-key path for hosts that cannot open a browser. Signup drops the password and the typed ORCID iD: it is the same device flow followed by guided completion of the fields the server reports missing (username suggestion, GitHub handle, city, country, then the upload access request), each with a flag for scripts.Other changes: accounts are keyed by username or email (a brand-new ORCID account has no username yet) and merged on re-login; a re-login replaces this machine's previous key;
nemar auth logoutrevokes only a device-minted key by default (--revoke-key/--no-revoke-key);nemar auth keys list|create|revoke;auth statusshows the key;retrieve-keyandregenerate-keyprint a deprecation sentence; the API client learns the device vocabulary so a person reads the sentence rather than a code;device_codeis redacted from debug logs;confirm()declines cleanly without a TTY; Ctrl-C mid-poll aborts the in-flight request and exits 130 with the previous config untouched. Two small backend touches:GET /auth/profile/username-suggestionaccepts a bearer, and the brand-new-account ORCID redirect to/auth/orcid/completecarries?next=so the website (nemarOrg/website#317) can return the person to the authorize page.Closes #1283
Part of epic #1272
Test plan
test/auth-device-cli.test.ts(41 cases, realbun run src/index.tsagainst aBun.servestand-in): printed URL and code; browser attempted only when allowed; pending thenslow_downhonoured; expiry and denial as one sentence plus next step with no config write; success writes a 0600 config thatauth statusreads; SIGINT mid-poll leaves the config byte-identical and exits 130; two logins in flight;--keyrefused before any write; a 0644 config becomes 0600; logout revoke rules; keys list/create/revoke; signup with flags and its non-TTY refusal; deprecation lines; root shortcuts; debug log redactiontest/device-login.unit.test.ts,test/api-export-surface.unit.test.ts,test/debug-log-cli.test.tsupdated;backend/test/profile-username-route.test.tsandbackend/test/device-auth-routes.test.tscover the two backend touchesbun run lint,bun run typecheck; fullbun testmatches the pre-existing baseline (the same 50 credential-dependent live-tier failures, none new)configFileMode, the username-or-email key, the logoutkeySourcecheck, the non-TTY guard; each mutation caught, each revertedtest/auth-device-cli-live.test.tsruns against the dev worker once the epic reachesdev(it probe-skips until then)ssh mcmandssh mba, including a headless run over ssh with the code entered on the laptop, recorded on Phase 3: CLI login and signup on the device flow #1283 after deployment